<?php
require $_SERVER['DOCUMENT_ROOT'].'/vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
function generate_urlsigndownload($bucket, $objectKey, $accessKeyId, $secretAccessKey)
{
    $region = 'rainyun';
    $s3Client = new S3Client([
        'version' => 'latest',
        'region' => $region,
        'endpoint' => 'https://cn-sy1.rains3.com',
        'credentials' => [
            'key' => $accessKeyId,
            'secret' => $secretAccessKey
        ],
        'use_path_style_endpoint' => true,
        'suppress_php_deprecation_warning' => true
    ]);

    $command = $s3Client->getCommand('GetObject', [
        'Bucket' => $bucket,
        'Key' => $objectKey
    ]);

    try {
        $presignedUrl = (string) $s3Client->createPresignedRequest($command, '+1 hour')->getUri();
        return $presignedUrl;
    } catch (AwsException $e) {
        return "Error: " . $e->getMessage();
    }
}
function delete_urlsigndownload($bucket, $objectKey, $accessKeyId, $secretAccessKey)
{
    $region = 'rainyun';
    $s3Client = new S3Client([
        'version' => 'latest',
        'region' => $region,
        'endpoint' => 'https://cn-sy1.rains3.com',
        'credentials' => [
            'key' => $accessKeyId,
            'secret' => $secretAccessKey
        ],
        'http' => [
            'verify' => false,
        ],
        'use_path_style_endpoint' => true,
        'suppress_php_deprecation_warning' => true
    ]);

    try {
        $s3Client->deleteObject([
            'Bucket' => $bucket,
            'Key' => $objectKey
        ]);
    } catch (AwsException $e) {
        echo json_encode(['error' => 'Error: ' . $e->getMessage(), 'status' => 0]);
    }
}
function filespace_delete($conn, $filesizeg, $userid)
{
    $file_size_gb = $filesizeg / (1024 * 1024 * 1024);
    $sql = "UPDATE user SET capacityed = capacityed - ? WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ds", $file_size_gb, $userid);
    if ($stmt->execute()) {
        return true;
    } else {
        return false;
    }
}
require($_SERVER['DOCUMENT_ROOT'] . '/setting.php');
function verifyToken($token)
{
    global $redis_pz;
    $redis = new Redis();
    $redis->connect($redis_pz['host'], $redis_pz['port']);
    $redis->auth($redis_pz['password']);
    $data = $redis->get($token);
    if ($data) {
        $data = json_decode($data, true);
        if ($data['timestamp'] > time()) {
            return true;
        }
    }
    return false;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'error: requests are not allowed']);
    exit;
}
require($_SERVER['DOCUMENT_ROOT'] . '/cofd/functions.php');
$data_y = file_get_contents("php://input");
$data_x = json_decode($data_y, true);
$token  = $data_x['token'];
if ($token != '') {
    $token  = encrypt($token, 'D', 'yhsdylpo9342');
} else {
    echo json_encode(['success' => false, 'message' => 'error: invalid token']);
    exit;
}
if (!verifyToken($token)) {
    echo json_encode(['success' => false, 'message' => 'error: invalid token']);
    exit;
}
require($_SERVER['DOCUMENT_ROOT'] . '/cofd/common.php');
require($_SERVER['DOCUMENT_ROOT'] . '/setting.php');
$user_id = $data_x['userid'];
$fileid = encrypt($data_x['fileid'],'D','yhsdylpo9342');
$sql = "SELECT names,asets FROM `files` WHERE id = ? AND `froms` = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $fileid, $user_id);
if ($stmt->execute()) {
    $result = $stmt->get_result();
    if ($result) {
        $row = $result->fetch_assoc();
        $real_path = $_SERVER['DOCUMENT_ROOT'] . '/uploads/' . $row['asets'];
        if (substr($row['asets'], 0, 5) == 's3::>') {
            $temp_path = generate_urlsigndownload($rainyun_oss['bucket'], $fileid . '_' . $row['names'], $rainyun_oss['access_key_id'], $rainyun_oss['access_key_secret']);
            $headers = @get_headers($temp_path, 1);
            if (!isset($headers['Content-Length'])) {
                echo json_encode(['error' => 'Cannot determine file size', 'status' => 0]);
                curl_close($ch);
                exit;
            }
            $file_size = intval($headers['Content-Length']);
            if (filespace_delete($conn,$file_size,$user_id)) {
                delete_urlsigndownload($rainyun_oss['bucket'], $fileid . '_' . $row['names'], $rainyun_oss['access_key_id'], $rainyun_oss['access_key_secret']);
                $sql = "DELETE FROM `files` WHERE id = ? AND `froms` = ?";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param("ss", $fileid, $user_id);
                if ($stmt->execute()) {
                    echo json_encode(['success' => true]);
                } else {
                    echo json_encode(['success' => false, 'message' => 'error: database error']);
                }
            } else {
                echo json_encode(['success' => false, 'message' => 'error: file not found']);
            }
        } else {
            $file_size = filesize($real_path);
            if (filespace_delete($conn,$file_size,$user_id)) {
                if (unlink($real_path)) {
                    $sql = "DELETE FROM `files` WHERE id = ? AND `froms` = ?";
                    $stmt = $conn->prepare($sql);
                    $stmt->bind_param("ss", $fileid, $user_id);
                    if ($stmt->execute()) {
                        echo json_encode(['success' => true]);
                    } else {
                        echo json_encode(['success' => false, 'message' => 'error: database error']);
                    }
                } else {
                    echo json_encode(['success' => false, 'message' => 'error: file not found']);
                }
            } else {
                echo json_encode(['success' => false, 'message' => 'error: file not found']);
            }
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'error: database error']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'error: database error']);
}
$stmt->close();
$conn->close();
